import type { AdminModel } from '@/apis/types/admin'
import {
  updateAdminApi,
  updateAdminResetGoogleSecretApi,
} from '@/apis/modules/admin'
import { ModalHelper } from '@/utils/modal.helper'
import { Message } from '@arco-design/web-vue'

export function useCommands(loading: Ref<boolean>) {
  const {
    visible: editorVisible,
    data: editorState,
    open: openEditor,
  } = usePopup<AdminModel>()
  const {
    visible: resetPwdVisible,
    data: resetPwdState,
    open: openResetPwd,
  } = usePopup<AdminModel>()
  // 刷新
  const refreshResult = createEventHook()
  /** 添加管理员 */
  function onCreate() {
    openEditor()
  }
  /** 重置密码 */
  function onResetPwd(record: AdminModel) {
    openResetPwd(record)
  }
  /** 重置谷歌密钥 */
  function onResetKey(record: AdminModel) {
    const request = () => {
      return new Promise<void>((resolve, reject) => {
        loading.value = true
        updateAdminResetGoogleSecretApi({
          id: record?.id ?? '',
        })
          .then(() => {
            Message.success('操作成功')
            refreshResult.trigger()
            resolve()
          })
          .finally(() => {
            loading.value = false
          })
          .catch(e => reject(e))
      })
    }

    ModalHelper.error(
      {
        title: '重置谷歌密钥',
        content:
          '重置密钥后，账号需重新绑定新的密钥才能登录，请确认是否重置该账号的密钥？',
        width: 480,
        closable: false,
      },
      request,
    )
  }
  /** 切换状态 */
  function onChangeStatus(record: AdminModel) {
    const request = () => {
      return new Promise<void>((resolve, reject) => {
        loading.value = true
        updateAdminApi({
          id: record?.id ?? '',
          status: record?.status === 1 ? 2 : 1,
        })
          .then(() => {
            Message.success(record?.status === 1 ? '禁用成功' : '启用成功')
            refreshResult.trigger()
            resolve()
          })
          .finally(() => {
            loading.value = false
          })
          .catch(e => reject(e))
      })
    }

    if (record?.status !== 1) {
      request()
    } else {
      ModalHelper.error(
        {
          width: '400px',
          okText: '禁用',
          title: '禁用账户',
          content: '确定要禁用该账户吗？禁用后，账户将被禁止登录。',
        },
        request,
      )
    }
  }
  return {
    editorVisible,
    editorState,
    resetPwdVisible,
    resetPwdState,
    onCreate,
    onResetPwd,
    onResetKey,
    onChangeStatus,
    onRefresh: refreshResult.on,
  }
}
